package com.yiwei.zxp.util;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import java.io.File;

/**
 * Created by xsooy-pc on 18-1-11.
 */

public class DownloadUtil {
    public static void downloadReport(Context context, long myDwonloadID) {
        try {
            if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上
                File file = queryDownloadedReport(context);
                Uri apkUri = FileProvider.getUriForFile(context, "com.yiwei.zxp.fileprovider", file);
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addCategory("android.intent.category.DEFAULT");
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/pdf");
                context.startActivity(install);
            } else {
                if (Build.VERSION.SDK_INT >= 23) {
                    try {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        File apkFile = queryDownloadedReport(context);
                        install.addCategory("android.intent.category.DEFAULT");
                        install.setDataAndType(Uri.fromFile(apkFile), "application/pdf");
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(install);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        Uri downloadFileUri = ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE))
                                .getUriForDownloadedFile(myDwonloadID);
                        install.addCategory("android.intent.category.DEFAULT");
                        install.setDataAndType(downloadFileUri,
                                "application/pdf");
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(install);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //通过downLoadId查询下载的apk，解决6.0以后安装的问题
    public static File queryDownloadedReport(Context context) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        long downloadId = PreferenceUtils.getLong(context, "downloadReportId", 0);
        if (downloadId != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!TextUtils.isEmpty(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }

    public static void installApp(Context context, long myDwonloadID) {
        try {


            if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上
                File file = queryDownloadedApk(context);
                Uri apkUri = FileProvider.getUriForFile(context, "com.yiwei.zxp.fileprovider", file);
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                context.startActivity(install);
            } else {
                if (Build.VERSION.SDK_INT >= 23) {
                    try {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        File apkFile = queryDownloadedApk(context);
                        install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(install);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        Uri downloadFileUri = ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE))
                                .getUriForDownloadedFile(myDwonloadID);
                        install.setDataAndType(downloadFileUri,
                                "application/vnd.android.package-archive");
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(install);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //通过downLoadId查询下载的apk，解决6.0以后安装的问题
    private static File queryDownloadedApk(Context context) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        long downloadId = PreferenceUtils.getLong(context, "downloadId", 0);
        if (downloadId != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!TextUtils.isEmpty(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }
}
